from pyx import *
import os
import sys

def plot_data(input_data, input_clusters, output_file):
    dataFile = open(input_data,"r")
    clusterFile = open(input_clusters,"r")
   
    #Skip the first line that contains the value of the
    #clusters' quality
    #quality = float(clusterFile.readline())
    quality = clusterFile.readline()
    
    #Read all the clusters and store them in a list
    n_c = int(clusterFile.readline())
    clusters = []
    for i in range(n_c):
        line = clusterFile.readline()
        clusters.append(lineToList(line))
        
    #Read all data and separete it by it's cluster
    data = [[] for i in range(n_c)]

    for line in dataFile.readlines():
        clust = int(clusterFile.readline())
        data[clust].append(lineToList(line))

    auxFiles = []
    for i in range(n_c):
        auxFiles.append( plotPoints(i,data[i]) )

    auxFiles.append(plotPoints(n_c,clusters))

    g = graph.graphxy( width=30, height=30, x=graph.axis.lin(min=-1000,max=1000, title=r"$x$-axis"), y=graph.axis.lin(min=-1000,max=1000, title=r"$y$-axis"))

    g.plot([graph.data.file(fn, x=1, y=2) for fn in auxFiles],[graph.style.symbol(symbolattrs=[color.gradient.Rainbow])])

    g.writePDFfile(output_file)

    for i in auxFiles:
        os.system("rm "+i)

def lineToList(line):
    return map( float ,line.split(","))

def plotPoints(i,data):
    fileName = "auxFile"+str(i)+".aux"
    f = open(fileName,"w")
    for i in data:
        line = " ".join( map(str,i) )
        f.write(line+'\n')
    if len(data)==0:
        f.write("1000 1000\n")
    f.close()
    return fileName

if __name__ == "__main__":
    probName = sys.argv[1]
    plot_data(probName+".data",probName+".clusters",probName+".sol.pdf")
